import Area from './Area.js'
import PixPoint from './PixPoint.js'
import Vector2 from './Vector2.js'

export default class Sprite extends Area {
  img: HTMLImageElement
  outBorder: Array<Vector2> = new Array<Vector2>()
  constructor(x: number = 0, y: number = 0, width: number = 0, height: number = 0, imgPath: string = '') {
    super(x, y, width, height)
    this.img = new Image()
    this.img.src = imgPath
  }
  initOutBorder(context: CanvasRenderingContext2D) {
    this.img.onload = () => {
      context.drawImage(this.img, this.x, this.y, this.width, this.height)
      let imgData = context.getImageData(this.x, this.y, this.width, this.height)
      let bitArr = imgData.data
      let pixArr = new Array<PixPoint>()
      for (let i = 0; i < bitArr.length; i += 4) {
        let x = (i / 4) % this.width
        let y = Math.floor(i / 4 / this.width)
        pixArr.push(new PixPoint(x, y, bitArr[i], bitArr[i + 1], bitArr[i + 2], bitArr[i + 3]))
      }

      this.outBorder = pixArr.filter((e, i, arr) => {
        return (
          (arr[i - 1]?.a === 0 && e.a !== 0) ||
          (arr[i + 1]?.a === 0 && e.a !== 0) ||
          (arr[i - this.width] && arr[i - this.width]?.a === 0 && e.a !== 0) ||
          (arr[i + this.width] && arr[i + this.width]?.a === 0 && e.a !== 0) ||
          (!arr[i - this.width] && e.a !== 0) ||
          (!arr[i + this.width] && e.a !== 0) ||
          (!arr[i - 1] && e.a !== 0) ||
          (!arr[i + 1] && e.a !== 0)
        )
      })
      .map(e=> new Vector2(e.x,e.y))
      // context.clearRect(this.x, this.y, this.width, this.height)
    }
  }
  // showBorder(context: CanvasRenderingContext2D) {
  //   this.outBorder.forEach(e => {
  //     context.fillStyle = `rgba(${e.r},${e.g},${e.b},${e.a})`
  //     context.fillRect(this.x + e.x, this.y + e.y, 1, 1)
  //   })
  // }
  draw(context: CanvasRenderingContext2D) {
    context.drawImage(this.img, this.x, this.y, this.width, this.height)
  }
  onCollision(other:Sprite):boolean{
    let result = false
    for(let i = 0 ; i < this.outBorder.length; i++){
      if(result) break
      for(let j = 0; j < other.outBorder.length; j++){
        if(this.outBorder[i].offset(this.x,this.y).compare(other.outBorder[j].offset(other.x,other.y))) {
          // console.log(this.outBorder[i].string,other.outBorder[j].string)
          result = true
          break
        }
      }
    }
    return result
  }
}
